<?php

namespace app\controllers;
use yii\data\ActiveDataProvider;
use yii\filters\auth\QueryParamAuth;
use app\models\Car;
use app\models\User;
use Yii;

class CarController extends \yii\rest\ActiveController
{
	public $modelClass = 'app\models\Car'; 

    public $serializer = [
         'class' => 'yii\rest\Serializer',
         'collectionEnvelope' => 'items'
     ];

/* public function actions() {
        return [
            'test' => [
                'class' => 'app\controllers\action\CarAction',
                'modelClass' => $this->modelClass,
            ],*/

//控制请求的方式
      protected function verbs(){
        return [
            'index' => ['GET', 'HEAD'],
            'view' => ['GET', 'HEAD'],
            'create' => ['POST'],
            'update' => ['PUT', 'PATCH'],
            'delete' => ['DELETE'],
        ];
    }

     public function actions()
     {
         $actions = parent::actions();
         // 注销系统自带的实现方法
         unset($actions['index'],  $actions['create'], $actions['update'],$actions['delete'], $actions['view']);
         return $actions;
     }


	public function behaviors()
    {
        return \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            //响应返回json
            'contentNegotiator' => [
                'formats' => [
                    'application/json' => \yii\web\Response::FORMAT_JSON,
                ],
            ],
            
           //接口采用参数带token的方式进行认证 
            'authenticator' => [
            'class' => QueryParamAuth::classname(), 
                     
           
    ]
    ]);
    }

public function actionIndex()
     {
         $modelClass = $this->modelClass;
         $query = $modelClass::find();
         return new ActiveDataProvider([
             'query' => $query
         ]);
     }
 
     public function actionCreate()
     {
         $model = new $this->modelClass();
         // $model->load(Yii::$app->getRequest()
         // ->getBodyParams(), '');
         $model->attributes = Yii::$app->request->post();
         $model->save();
         if (! $model->save()) {
             return array_values($model->getFirstErrors())[0];
         }
        return $model;
     }
 
     public function actionUpdate($id)
     {
         $model = $this->findModel($id);
         $model->attributes = Yii::$app->request->post();
         if (! $model->save()) {
             return array_values($model->getFirstErrors())[0];
         }
         return $model;
     }
 
     public function actionDelete($id)
     {
         return $this->findModel($id)->delete();
     }
 
     public function actionView($id)
    {
         return $this->findModel($id);
     }

     protected function findModel($id)
     {
         $modelClass = $this->modelClass;
         if (($model = $modelClass::findOne($id)) !== null) {
             return $model;
         } else {
             throw new NotFoundHttpException('The requested page does not exist.');
         }
     }


    //自定义的search方法

    public function actionSearch()
{
    if (isset($_POST["user_id"])) {
        $model = new $this->modelClass;
        $query = $model::find()
        ->where(['user_id' => $_POST["user_id"]]);
        try {
            $provider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => false
            ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
        if ($provider->getCount() <= 0) {
            throw new \yii\web\HttpException(404, '没有找到结果');
        } else {
            return $provider;
        }
    } else {
        throw new \yii\web\HttpException(400, '请输入正确的参数！');
               
          }
}



     public function actionBd()
     {

         if (!isset($_POST["user_id"])||!isset($_POST["car_number"]))
         {  throw new \yii\web\HttpException(400, '请填写正确的参数！');}

        try {
            $car =Car::findOne([
     'car_number' => $_POST["car_number"]
         ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
       if($car!=null)
        throw new \yii\web\HttpException(400, '对不起，该号牌已绑定过！');


        try {
            $caruser =User::findOne([
     'id' => $_POST["user_id"]
         ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
      
    if($caruser===null)
    	 throw new \yii\web\HttpException(400, '对不起，记录中没有这位车主！');
         $model = new $this->modelClass;
         // $model->load(Yii::$app->getRequest()
         // ->getBodyParams(), '');
         $model->attributes = Yii::$app->request->post();
         $model->save();
         if (! $model->save()) {
             return array_values($model->getFirstErrors())[0];
         }
        return $model;
     }
     
     
     public function actionGzxg()
     {
       //车牌号作为唯一标识
         if (!isset($_POST["car_number"])||!isset($_POST["user_id"]))
         {  throw new \yii\web\HttpException(400, '请填写正确的参数！');}
       
         try {
            $car =Car::findOne(
                ['car_number' => $_POST["car_number"],
                 'user_id' => $_POST["user_id"]
                ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
        if($car===null)
        {   throw new \yii\web\HttpException(404, '该车辆没有注册绑定或者你没有修改信息的权限！');                 }
        
         $car->attributes = Yii::$app->request->post();
         $car->save();
         if (! $car->save()) {
             return array_values($car->getFirstErrors())[0];
         }
          $a=1;
          $b=1;
          $c=1;
          $d=1;
          $e=1;
        if($car->engine==0)
            $a=0;
        if($car->gearbox==0)
            $b=0;
        if($car->light==0)
            $c=0;
        if($car->mileage%15000==0)
            $d=0;
        if($car->oil_percent<20)
            $e=0;
        $R=$a+10*$b+100*$c+1000*$d+10000*$e;

        if($R!=11111)
            throw new \yii\web\HttpException(409, $car->car_number,$R);


         
        
     }
     
     
     
     
     
      public function actionJcbd()
     {

     	 if (!isset($_POST["id"])||!isset($_POST["user_id"]))
         { throw new \yii\web\HttpException(400, '请填写正确的参数！');}
     	 try {
            $car =Car::findOne([
     'id' => $_POST["id"],
     'user_id' => $_POST["user_id"]          ]);
        } catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }
      
    if($car===null)
    { throw new \yii\web\HttpException(400, '对不起，没有这辆车！');}
    	
        try{
         Car::findOne([
     'id' => $_POST["id"]])->delete();}
         catch (Exception $ex) {
            throw new \yii\web\HttpException(500, 'Internal server error');
        }


     }


     
}
